package com.bridge.common.weight;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;

import com.bridge.common.R;

/**
 * @说明： 自定义带删除按钮的EditText
 * 1.默认携带亮色和暗色两种删除按钮。
 * 2.可以通过android:drawableRight，自定义图标。
 * <p>
 * 2018-7-2 修改:
 * 1.原代码 在没有焦点时会将删除图标隐藏,而如果ClearEditText有内容时,虽然图标隐藏,但点击 图标所在的位置,还是会响应操作;
 * 最合理的做法应该是只要它有数据,就显示图标
 * 2.加入左侧padding值
 * 3:enable时点击删除图标才能删除数据,否则不能删除
 */
@SuppressLint("AppCompatCustomView")
public class ClearEditText extends EditText implements View.OnFocusChangeListener,
        TextWatcher {
    //EditText右侧的删除按钮  
    private Drawable mClearDrawable, emptyDrawable;
    private boolean hasFoucs;

    public ClearEditText(Context context) {
        this(context, null);
    }

    public ClearEditText(Context context, AttributeSet attrs) {
        this(context, attrs, android.R.attr.editTextStyle);
//        init(context, attrs);
    }

    public ClearEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs);
    }

    private boolean isLightIcon;

    private void init(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ClearEditText);
        isLightIcon = typedArray.getBoolean(R.styleable.ClearEditText_lightIcon, false);//是否使用默认的亮色图标。

        // 获取EditText的DrawableRight,假如没有设置我们就使用默认的图片,获取图片的顺序是左上右下（0,1,2,3,）  
        mClearDrawable = getCompoundDrawables()[2];
        if (mClearDrawable == null) {
            if (isLightIcon) {
                mClearDrawable = getResources().getDrawable(
                        R.mipmap.delete);
            } else {
                mClearDrawable = getResources().getDrawable(
                        R.mipmap.delete);
            }
        }

        mClearDrawable.setBounds(0, 0, mClearDrawable.getIntrinsicWidth(),
                mClearDrawable.getIntrinsicHeight());

        emptyDrawable = getContext().getResources().getDrawable(R.mipmap.empty);
        emptyDrawable.setBounds(0, 0, emptyDrawable.getIntrinsicWidth(),
                emptyDrawable.getIntrinsicHeight());
        // 默认设置隐藏图标
        setClearIconVisible(false);
        // 设置焦点改变的监听  
        setOnFocusChangeListener(this);
        // 设置输入框里面内容发生改变的监听  
        addTextChangedListener(this);
        setPadding(context);
        typedArray.recycle();
    }

    public static int dpToPxInt(Context mContext , float dp) {
        if (mContext == null) {
            return -1;
        }
        float v = dp * mContext.getResources().getDisplayMetrics().density;
        return (int) (v + 0.5f);
    }

    private void setPadding(Context mContext) {
        setPadding(dpToPxInt(mContext ,5), 0, dpToPxInt(mContext ,4), 0);// 设置右侧图片，距离右侧边距。
    }

    /* @说明：isInnerWidth, isInnerHeight为ture，触摸点在删除图标之内，则视为点击了删除图标
     * event.getX() 获取相对应自身左上角的X坐标 
     * event.getY() 获取相对应自身左上角的Y坐标 
     * getWidth() 获取控件的宽度 
     * getHeight() 获取控件的高度 
     * getTotalPaddingRight() 获取删除图标左边缘到控件右边缘的距离 
     * getPaddingRight() 获取删除图标右边缘到控件右边缘的距离 
     * isInnerWidth: 
     *  getWidth() - getTotalPaddingRight() 计算删除图标左边缘到控件左边缘的距离 
     *  getWidth() - getPaddingRight() 计算删除图标右边缘到控件左边缘的距离 
     * isInnerHeight: 
     *  distance 删除图标顶部边缘到控件顶部边缘的距离 
     *  distance + height 删除图标底部边缘到控件顶部边缘的距离 
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            if (getCompoundDrawables()[2] != null) {
                int x = (int) event.getX();
                int y = (int) event.getY();
                Rect rect = getCompoundDrawables()[2].getBounds();
                int height = rect.height();
                int distance = (getHeight() - height) / 2;
                boolean isInnerWidth = x > (getWidth() - getTotalPaddingRight()) && x < (getWidth() - getPaddingRight());
                boolean isInnerHeight = y > distance && y < (distance + height);
                if (isEnabled() && isInnerWidth && isInnerHeight) {
                    this.setText("");
                }
            }
        }
        return super.onTouchEvent(event);
    }

    /**
     * 当ClearEditText焦点发生变化的时候，
     * 输入长度为零，隐藏删除图标，否则，显示删除图标
     */
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        this.hasFoucs = hasFocus;
        setClearIconVisible(getText().length() > 0);
   /*     if (hasFocus) {
            setClearIconVisible(getText().length() > 0);
        } else {
            setClearIconVisible(false);
        }*/
    }

    protected void setClearIconVisible(boolean visible) {
        Drawable right;
        if (isEnabled()) {
            right = visible ? mClearDrawable : emptyDrawable;
        } else {
            right = emptyDrawable;
        }
        setCompoundDrawables(getCompoundDrawables()[0],
                getCompoundDrawables()[1], right, getCompoundDrawables()[3]);
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int count, int after) {
     /*   if (hasFoucs) {
            setClearIconVisible(s.length() > 0);
        }*/

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        setClearIconVisible(s.length() > 0);
    }


} 